﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using SharpDiary.Core.Drawing;

namespace SharpDiary.Core.Controls
{
    [DefaultEvent("CheckedStateChanged")]
    public partial class OnOffButtonControl : UserControl
    {
        private bool _checked = false;

        /// <summary>
        /// 是否启用。
        /// </summary>
        public bool Checked
        {
            get { return _checked; }
            set
            {
                _checked = value; Invalidate();
                this.BackColor = (_checked ? Color.FromKnownColor(KnownColor.Highlight) : Color.FromKnownColor(KnownColor.ButtonShadow));
            }
        }

        public event EventHandler<EventArgs> CheckedStateChanged;

        protected virtual void OnCheckedStateChanged(object sender, EventArgs e)
        {
            if (CheckedStateChanged != null) { CheckedStateChanged(sender, e); }
        }

        public OnOffButtonControl()
        {
            InitializeComponent();

            ResizeRedraw = true;
            DoubleBuffered = true;
        }

        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            base.OnPaintBackground(e);

            Rectangle buttonRect = new Rectangle((_checked ? new Point((int)(Width * 0.6f), 0) : new Point(0, 0)), new Size((int)(Width * 0.4f), Height));
            Rectangle textRect = new Rectangle((_checked ? new Point(0, 0) : new Point((int)(Width * 0.4f), 0)), new Size((int)(Width * 0.6f), Height));

            ControlPaint.DrawButton(e.Graphics, buttonRect, ButtonState.Normal);
            TextRenderer.DrawText(e.Graphics, (_checked ? "开" : "关"), this.Font, textRect, this.ForeColor);
            ControlPaint.DrawBorder3D(e.Graphics, ClientRectangle, Border3DStyle.SunkenOuter);
        }

        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);

            Checked = !_checked;
            OnCheckedStateChanged(this, EventArgs.Empty);
        }
    }
}
